//
//  CancellationViewController.swift
//  EasyDana
//
//  Created by mac on 2024/10/18.
//

import UIKit
import RxSwift
import RxCocoa
class CancellationViewController: UIViewController {
    let cancel = PublishSubject<Bool>()
    private let bag = DisposeBag()
    private let agree = BehaviorRelay<Bool>.init(value: false)
    @IBOutlet weak var agreeView: UIImageView!
    @IBAction func agreeCancelAction(_ sender: UIButton) {
        self.agree.accept(!self.agree.value)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.agree
            .map { agree in
                if agree {
                    return UIImage(named: "login_agree_check")
                } else {
                    return UIImage(named: "login_agree_uncheck")
                }
            }
            .bind(to: self.agreeView.rx.image)
            .disposed(by: self.bag)
        // Do any additional setup after loading the view.
    }
    @IBAction func closeAction(_ sender: UIButton) {
        self.dismiss(animated: false)
    }
    
    @IBAction func cancelAction(_ sender: UIButton) {
        if self.agree.value == true {
            Task {
                do {
                    self.showLoading(text: nil)
                    let res = try await HTTPManager.default.post(path: Api.cancel, param: nil, dataType: [Int].self)
                    self.hideLoading()
                    if res.code == 0 {
                        UserDefaults.standard.removeObject(forKey: "session_id")
                        //回到首页
                        self.dismiss(animated: true) {
                            self.cancel.onNext(true)
                        }
                    } else {
                        self.show(toast: res.state)
                    }
                } catch {
                    self.hideLoading()
                }
            }
        }
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
